package server;

import codec.FileRequest;
import codec.FileRespond;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import java.io.File;
import java.io.RandomAccessFile;

/**
 * Created by ryan on 15-8-25.
 */
public class FileServerIoHandler extends IoHandlerAdapter {

    private long start;

    public void sessionCreated(IoSession session) throws Exception {
    }

    public void sessionOpened(IoSession session) throws Exception {
        FileRequest frq = new FileRequest(0);
        session.write(frq);
        start = System.nanoTime();
    }

    public void sessionClosed(IoSession session) throws Exception {
    }

    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
    }

    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {

    }

    public void messageReceived(IoSession session, Object message) throws Exception {
        //System.out.println("Received");
        FileRespond rep = (FileRespond) message;

        //System.out.println(" " + rep.getOffset() + " " + rep.getLength());

        RandomAccessFile file = new RandomAccessFile(new File(FileServer.fileName), "rw");
        file.seek(rep.getOffset());
        file.write(rep.getContent());
        file.close();

        if (rep.getLength() != FileServer.BUFFER_SIZE) {
            System.out.println("Transmit OK");
            System.out.println("Time: " + (System.nanoTime() - start)/1000000000);
            //file.close();
            //session.close();
        } else {
            FileRequest frs = new FileRequest(rep.getRecord());
            session.write(frs);
        }
    }
}
